package com.zenithmind.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.utils.BeanCopyUtils;
import com.zenithmind.task.enums.TaskType;
import com.zenithmind.task.mapper.TaskMapper;
import com.zenithmind.task.pojo.entity.Task;
import com.zenithmind.task.pojo.query.TaskQuery;
import com.zenithmind.task.pojo.vo.TaskVO;
import com.zenithmind.task.service.TaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Override
    public PageResult<TaskVO> getTaskPage(TaskQuery query, String userId) {
        Page<Task> page = query.toPage();

        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();

        // 基础查询条件
        wrapper.like(StringUtils.hasText(query.getTitle()), Task::getTitle, query.getTitle())
               .like(StringUtils.hasText(query.getDescription()), Task::getDescription, query.getDescription())
               .in(query.getStatusList() != null && !query.getStatusList().isEmpty(), Task::getStatus, query.getStatusList())
               .in(query.getPriorityList() != null && !query.getPriorityList().isEmpty(), Task::getPriority, query.getPriorityList())
               .in(query.getTaskTypeList() != null && !query.getTaskTypeList().isEmpty(), Task::getTaskType, query.getTaskTypeList())
               .in(query.getCategoryIds() != null && !query.getCategoryIds().isEmpty(), Task::getCategoryId, query.getCategoryIds())
               .in(query.getCreatorIds() != null && !query.getCreatorIds().isEmpty(), Task::getCreatorId, query.getCreatorIds())
               .in(query.getAssigneeIds() != null && !query.getAssigneeIds().isEmpty(), Task::getAssigneeId, query.getAssigneeIds())
               .in(query.getProjectIds() != null && !query.getProjectIds().isEmpty(), Task::getProjectId, query.getProjectIds())
               .eq(StringUtils.hasText(query.getParentId()), Task::getParentId, query.getParentId());

        // 时间范围查询
        if (query.getPlannedStartTimeBegin() != null) {
            wrapper.ge(Task::getPlannedStartTime, query.getPlannedStartTimeBegin());
        }
        if (query.getPlannedStartTimeEnd() != null) {
            wrapper.le(Task::getPlannedStartTime, query.getPlannedStartTimeEnd());
        }
        if (query.getPlannedEndTimeBegin() != null) {
            wrapper.ge(Task::getPlannedEndTime, query.getPlannedEndTimeBegin());
        }
        if (query.getPlannedEndTimeEnd() != null) {
            wrapper.le(Task::getPlannedEndTime, query.getPlannedEndTimeEnd());
        }
        if (query.getCreateTimeBegin() != null) {
            wrapper.ge(Task::getCreateTime, query.getCreateTimeBegin());
        }
        if (query.getCreateTimeEnd() != null) {
            wrapper.le(Task::getCreateTime, query.getCreateTimeEnd());
        }

        // 进度范围查询
        if (query.getProgressMin() != null) {
            wrapper.ge(Task::getProgress, query.getProgressMin());
        }
        if (query.getProgressMax() != null) {
            wrapper.le(Task::getProgress, query.getProgressMax());
        }

        // 布尔条件查询
        if (query.getIsImportant() != null) {
            wrapper.eq(Task::getIsImportant, query.getIsImportant() ? 1 : 0);
        }
        if (query.getIsUrgent() != null) {
            wrapper.eq(Task::getIsUrgent, query.getIsUrgent() ? 1 : 0);
        }

        // 关键词搜索
        if (StringUtils.hasText(query.getKeyword())) {
            wrapper.and(w -> w.like(Task::getTitle, query.getKeyword())
                             .or()
                             .like(Task::getDescription, query.getKeyword()));
        }

        // 排序
        wrapper.orderByDesc(Task::getCreateTime);

        IPage<Task> result = page(page, wrapper);

        List<TaskVO> voList = result.getRecords().stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    public TaskVO getTaskById(String id, String userId) {
        Task task = getById(id);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }
        
        return convertToVO(task, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTask(Task task, String userId) {
        // 设置创建者信息
        task.setCreatorId(userId);
        
        // 设置默认值
        if (task.getStatus() == null) {
            task.setStatus(1); // 待办
        }
        if (task.getPriority() == null) {
            task.setPriority(2); // 中等优先级
        }
        if (task.getProgress() == null) {
            task.setProgress(0);
        }
        if (task.getCompletionRate() == null) {
            task.setCompletionRate(0);
        }
        
        // 设置任务路径（用于子任务）
        if (StringUtils.hasText(task.getParentId())) {
            Task parentTask = getById(task.getParentId());
            if (parentTask != null) {
                task.setLevel(parentTask.getLevel() + 1);
                task.setPath(parentTask.getPath() + "/" + task.getId());
            }
        } else {
            task.setLevel(1);
            task.setPath("/" + task.getId());
        }
        
        boolean result = save(task);
        
        if (result) {
            log.info("用户 {} 创建任务: {}", userId, task.getTitle());
            // 发送通知、记录日志等
            sendTaskNotification(task, "CREATED", userId);
            recordTaskLog(task.getId(), "CREATED", "任务已创建", userId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTask(Task task, String userId) {
        Task existingTask = getById(task.getId());
        if (existingTask == null) {
            throw new BusinessException("任务不存在");
        }
        
        // 权限检查
        if (!checkTaskPermission(existingTask, userId, "edit")) {
            throw new BusinessException("无权限编辑该任务");
        }
        
        boolean result = updateById(task);
        
        if (result) {
            log.info("用户 {} 更新任务: {}", userId, task.getTitle());
            // 记录变更日志、发送通知等
            sendTaskNotification(task, "UPDATED", userId);
            recordTaskLog(task.getId(), "UPDATED", "任务已更新", userId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTask(String id, String userId) {
        Task task = getById(id);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }
        
        // 权限检查
        if (!checkTaskPermission(task, userId, "delete")) {
            throw new BusinessException("无权限删除该任务");
        }
        
        // 检查是否有子任务
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getParentId, id);
        long subtaskCount = count(wrapper);
        
        if (subtaskCount > 0) {
            throw new BusinessException("存在子任务，无法删除");
        }
        
        boolean result = removeById(id);
        
        if (result) {
            log.info("用户 {} 删除任务: {}", userId, task.getTitle());
            // 清理相关数据、发送通知等
            sendTaskNotification(task, "DELETED", userId);
            recordTaskLog(task.getId(), "DELETED", "任务已删除", userId);
            cleanupTaskRelatedData(task.getId(), userId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTaskStatus(String id, Integer status, String userId, String remark) {
        Task task = getById(id);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }
        
        // 权限检查
        if (!checkTaskPermission(task, userId, "edit")) {
            throw new BusinessException("无权限修改任务状态");
        }
        
        Integer oldStatus = task.getStatus();
        task.setStatus(status);
        
        // 根据状态设置时间
        LocalDateTime now = LocalDateTime.now();
        switch (status) {
            case 2: // 进行中
                if (task.getActualStartTime() == null) {
                    task.setActualStartTime(now);
                }
                break;
            case 3: // 已完成
                task.setActualEndTime(now);
                task.setProgress(100);
                task.setCompletionRate(100);
                break;
            case 4: // 已取消
            case 5: // 已暂停
                // 保持当前时间记录
                break;
        }
        
        boolean result = updateById(task);
        
        if (result) {
            log.info("用户 {} 将任务 {} 状态从 {} 更改为 {}", userId, task.getTitle(), oldStatus, status);
            // 记录状态变更日志、发送通知、更新父任务进度等
            sendTaskNotification(task, "STATUS_CHANGED", userId);
            recordTaskLog(task.getId(), "STATUS_CHANGED",
                String.format("状态从 %s 更改为 %s", getStatusText(oldStatus), getStatusText(status)), userId);
            updateParentTaskProgress(task.getParentId(), userId);
        }
        
        return result;
    }

    @Override
    public Boolean startTask(String id, String userId) {
        return updateTaskStatus(id, 2, userId, "开始任务");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean completeTask(String id, String userId, Double actualHours, String completionNote) {
        Task task = getById(id);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }
        
        if (actualHours != null) {
            task.setActualHours(java.math.BigDecimal.valueOf(actualHours));
        }
        
        boolean result = updateTaskStatus(id, 3, userId, completionNote);
        
        if (result && actualHours != null) {
            updateById(task);
        }
        
        return result;
    }

    @Override
    public Boolean pauseTask(String id, String userId, String reason) {
        return updateTaskStatus(id, 5, userId, reason);
    }

    @Override
    public Boolean cancelTask(String id, String userId, String reason) {
        return updateTaskStatus(id, 4, userId, reason);
    }

    @Override
    public PageResult<TaskVO> getMyTasks(TaskQuery query, String userId) {
        Page<Task> page = query.toPage();

        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAssigneeId, userId)
               .in(query.getStatusList() != null && !query.getStatusList().isEmpty(), Task::getStatus, query.getStatusList())
               .orderByDesc(Task::getCreateTime);

        IPage<Task> result = page(page, wrapper);

        List<TaskVO> voList = result.getRecords().stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());

        return new PageResult<>(voList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public List<TaskVO> getTodayTasks(String userId) {
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
        
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAssigneeId, userId)
               .in(Task::getStatus, 1, 2) // 待办或进行中
               .and(w -> w.between(Task::getPlannedStartTime, startOfDay, endOfDay)
                         .or()
                         .between(Task::getPlannedEndTime, startOfDay, endOfDay))
               .orderByAsc(Task::getPriority)
               .orderByAsc(Task::getPlannedEndTime);
        
        List<Task> tasks = list(wrapper);
        
        return tasks.stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());
    }

    // ==================== 辅助方法 ====================

    /**
     * 发送任务通知
     */
    private void sendTaskNotification(Task task, String action, String userId) {
        try {
            // TODO: 集成消息通知服务
            log.info("发送任务通知: taskId={}, action={}, userId={}", task.getId(), action, userId);
        } catch (Exception e) {
            log.error("发送任务通知失败", e);
        }
    }

    /**
     * 记录任务日志
     */
    private void recordTaskLog(String taskId, String action, String description, String userId) {
        try {
            // TODO: 集成任务日志服务
            log.info("记录任务日志: taskId={}, action={}, description={}, userId={}",
                    taskId, action, description, userId);
        } catch (Exception e) {
            log.error("记录任务日志失败", e);
        }
    }

    /**
     * 更新父任务进度
     */
    private void updateParentTaskProgress(String parentId, String userId) {
        if (StringUtils.hasText(parentId)) {
            try {
                // TODO: 实现父任务进度更新逻辑
                log.info("更新父任务进度: parentId={}, userId={}", parentId, userId);
            } catch (Exception e) {
                log.error("更新父任务进度失败", e);
            }
        }
    }

    /**
     * 清理任务相关数据
     */
    private void cleanupTaskRelatedData(String taskId, String userId) {
        try {
            // TODO: 清理任务相关数据（评论、附件、依赖关系等）
            log.info("清理任务相关数据: taskId={}, userId={}", taskId, userId);
        } catch (Exception e) {
            log.error("清理任务相关数据失败", e);
        }
    }

    /**
     * 设置任务关联数据
     */
    private void setTaskRelatedData(TaskVO vo, Task task, String userId) {
        try {
            // TODO: 设置子任务数量、评论数量、附件数量等
            log.debug("设置任务关联数据: taskId={}", task.getId());
        } catch (Exception e) {
            log.error("设置任务关联数据失败", e);
        }
    }

    /**
     * 检查是否会形成循环依赖
     */
    private boolean isCircularDependency(String taskId, String parentId) {
        if (!StringUtils.hasText(parentId)) {
            return false;
        }

        // 如果父任务ID等于当前任务ID，直接循环
        if (taskId.equals(parentId)) {
            return true;
        }

        // 递归检查父任务的父任务
        Task parent = getById(parentId);
        if (parent != null && StringUtils.hasText(parent.getParentId())) {
            return isCircularDependency(taskId, parent.getParentId());
        }

        return false;
    }

    /**
     * 转换为VO对象
     */
    private TaskVO convertToVO(Task task, String userId) {
        TaskVO vo = BeanCopyUtils.copyBean(task, TaskVO.class);
        
        // 设置状态文本
        vo.setStatusText(getStatusText(task.getStatus()));
        
        // 设置优先级文本和颜色
        vo.setPriorityText(getPriorityText(task.getPriority()));
        vo.setPriorityColor(getPriorityColor(task.getPriority()));
        
        // 设置任务类型文本
        TaskType taskType = task.getTaskType();
        vo.setTaskTypeText(taskType != null ? taskType.getName() : "未知");
        
        // 设置权限
        vo.setCanEdit(checkTaskPermission(task, userId, "edit"));
        vo.setCanDelete(checkTaskPermission(task, userId, "delete"));
        vo.setCanAssign(checkTaskPermission(task, userId, "assign"));
        
        // 设置时间相关
        if (task.getPlannedEndTime() != null) {
            LocalDateTime now = LocalDateTime.now();
            if (task.getPlannedEndTime().isBefore(now) && !task.getStatus().equals(3)) {
                vo.setIsOverdue(true);
                vo.setOverdueDays((int) java.time.Duration.between(task.getPlannedEndTime(), now).toDays());
            } else {
                vo.setIsOverdue(false);
                vo.setRemainingDays((int) java.time.Duration.between(now, task.getPlannedEndTime()).toDays());
            }
        }
        
        // 设置标签列表
        if (StringUtils.hasText(task.getTags())) {
            vo.setTagList(List.of(task.getTags().split(",")));
        }
        
        // 设置其他关联数据（子任务、评论、附件等）
        setTaskRelatedData(vo, task, userId);

        return vo;
    }

    /**
     * 检查任务权限
     */
    private Boolean checkTaskPermission(Task task, String userId, String action) {
        // 创建者拥有所有权限
        if (task.getCreatorId().equals(userId)) {
            return true;
        }
        
        // 负责人拥有编辑权限
        if (task.getAssigneeId() != null && task.getAssigneeId().equals(userId)) {
            return !"delete".equals(action);
        }
        
        // 检查协作者权限、项目权限等

        // 检查项目权限
        if (StringUtils.hasText(task.getProjectId())) {
            if (!checkProjectPermission(task.getProjectId(), userId, action)) {
                return false;
            }
        }

        // 检查协作者权限
        if (isTaskCollaborator(task.getId(), userId)) {
            return checkCollaboratorPermission(task.getId(), userId, action);
        }

        // 检查团队权限
        TaskType taskType = task.getTaskType();
        if (taskType != null && taskType.isTeam()) { // 团队任务
            return checkTeamPermission(task, userId, action);
        }

        return false;
    }

    /**
     * 检查项目权限
     */
    private boolean checkProjectPermission(String projectId, String userId, String action) {
        // TODO: 集成项目服务检查权限
        log.debug("检查项目权限: projectId={}, userId={}, action={}", projectId, userId, action);
        return true; // 暂时返回true
    }

    /**
     * 检查是否为任务协作者
     */
    private boolean isTaskCollaborator(String taskId, String userId) {
        // TODO: 查询任务协作者表
        log.debug("检查任务协作者: taskId={}, userId={}", taskId, userId);
        return false; // 暂时返回false
    }

    /**
     * 检查协作者权限
     */
    private boolean checkCollaboratorPermission(String taskId, String userId, String action) {
        // TODO: 根据协作者角色检查权限
        log.debug("检查协作者权限: taskId={}, userId={}, action={}", taskId, userId, action);
        return true; // 暂时返回true
    }

    /**
     * 检查团队权限
     */
    private boolean checkTeamPermission(Task task, String userId, String action) {
        // TODO: 检查用户是否在任务所属团队中
        log.debug("检查团队权限: taskId={}, userId={}, action={}", task.getId(), userId, action);
        return true; // 暂时返回true
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        switch (status) {
            case 1: return "待办";
            case 2: return "进行中";
            case 3: return "已完成";
            case 4: return "已取消";
            case 5: return "已暂停";
            default: return "未知";
        }
    }

    /**
     * 获取优先级文本
     */
    private String getPriorityText(Integer priority) {
        switch (priority) {
            case 1: return "低";
            case 2: return "中";
            case 3: return "高";
            case 4: return "紧急";
            default: return "未知";
        }
    }

    /**
     * 获取优先级颜色
     */
    private String getPriorityColor(Integer priority) {
        switch (priority) {
            case 1: return "#52c41a"; // 绿色
            case 2: return "#1890ff"; // 蓝色
            case 3: return "#fa8c16"; // 橙色
            case 4: return "#f5222d"; // 红色
            default: return "#d9d9d9"; // 灰色
        }
    }

    /**
     * 获取任务类型文本
     */
    private String getTaskTypeText(Integer taskType) {
        switch (taskType) {
            case 1: return "个人任务";
            case 2: return "团队任务";
            case 3: return "项目任务";
            default: return "未知";
        }
    }

    // ==================== 未实现的方法（返回默认值） ====================

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteTasks(List<String> ids, String userId) {
        for (String id : ids) {
            deleteTask(id, userId);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean assignTask(String taskId, String assigneeId, Integer assignmentType, Integer rolePermission, String note, String userId) {
        log.info("分配任务: taskId={}, assigneeId={}, assignmentType={}, userId={}",
                taskId, assigneeId, assignmentType, userId);

        // 验证参数
        if (!StringUtils.hasText(taskId) || !StringUtils.hasText(assigneeId)) {
            throw new BusinessException("任务ID和被分配人ID不能为空");
        }

        // 验证任务存在性
        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "assign")) {
            throw new BusinessException("无权限分配该任务");
        }

        // 更新任务分配信息
        String oldAssigneeId = task.getAssigneeId();
        task.setAssigneeId(assigneeId);
        task.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(task);

        if (result) {
            // 记录分配日志
            String logMessage = StringUtils.hasText(oldAssigneeId) ?
                String.format("任务重新分配给用户: %s", assigneeId) :
                String.format("任务分配给用户: %s", assigneeId);

            recordTaskLog(taskId, "ASSIGNED", logMessage, userId);
            sendTaskNotification(task, "ASSIGNED", userId);

            // TODO: 发送通知给新的被分配人
            log.info("任务分配成功: taskId={}, assigneeId={}", taskId, assigneeId);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchAssignTask(String taskId, List<String> assigneeIds, Integer assignmentType, String userId) {
        log.info("批量分配任务: taskId={}, assigneeIds={}, assignmentType={}, userId={}",
                taskId, assigneeIds, assignmentType, userId);

        // 验证参数
        if (!StringUtils.hasText(taskId) || assigneeIds == null || assigneeIds.isEmpty()) {
            throw new BusinessException("任务ID和被分配人列表不能为空");
        }

        // 验证任务存在性
        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "assign")) {
            throw new BusinessException("无权限分配该任务");
        }

        // TODO: 实现批量分配逻辑
        // 1. 创建任务分配记录表
        // 2. 为每个被分配人创建分配记录
        // 3. 发送通知给所有被分配人

        log.info("批量任务分配功能需要分配记录表支持，暂时返回成功");
        recordTaskLog(taskId, "BATCH_ASSIGNED",
                String.format("批量分配给 %d 个用户", assigneeIds.size()), userId);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unassignTask(String taskId, String assigneeId, String userId) {
        log.info("取消任务分配: taskId={}, assigneeId={}, userId={}", taskId, assigneeId, userId);

        if (!StringUtils.hasText(taskId)) {
            throw new BusinessException("任务ID不能为空");
        }

        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "assign")) {
            throw new BusinessException("无权限取消分配该任务");
        }

        // 如果指定了assigneeId，检查是否匹配
        if (StringUtils.hasText(assigneeId) && !assigneeId.equals(task.getAssigneeId())) {
            throw new BusinessException("指定的被分配人与当前分配不匹配");
        }

        String oldAssigneeId = task.getAssigneeId();
        task.setAssigneeId(null);
        task.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(task);

        if (result) {
            recordTaskLog(taskId, "UNASSIGNED",
                String.format("取消分配给用户: %s", oldAssigneeId), userId);
            sendTaskNotification(task, "UNASSIGNED", userId);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean acceptAssignment(String assignmentId, String userId) {
        log.info("接受任务分配: assignmentId={}, userId={}", assignmentId, userId);

        if (!StringUtils.hasText(assignmentId)) {
            throw new BusinessException("分配ID不能为空");
        }

        // TODO: 实现接受分配逻辑
        // 1. 查询分配记录
        // 2. 验证分配状态
        // 3. 更新分配状态为已接受
        // 4. 发送通知

        log.info("接受任务分配功能需要分配记录表支持，暂时返回成功");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean rejectAssignment(String assignmentId, String reason, String userId) {
        log.info("拒绝任务分配: assignmentId={}, reason={}, userId={}", assignmentId, reason, userId);

        if (!StringUtils.hasText(assignmentId)) {
            throw new BusinessException("分配ID不能为空");
        }

        // TODO: 实现拒绝分配逻辑
        // 1. 查询分配记录
        // 2. 验证分配状态
        // 3. 更新分配状态为已拒绝
        // 4. 记录拒绝原因
        // 5. 发送通知

        log.info("拒绝任务分配功能需要分配记录表支持，暂时返回成功");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTaskProgress(String id, Integer progress, String userId, String note) {
        Task task = getById(id);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "edit")) {
            throw new BusinessException("无权限更新任务进度");
        }

        // 验证进度范围
        if (progress < 0 || progress > 100) {
            throw new BusinessException("进度值必须在0-100之间");
        }

        task.setProgress(progress);

        // 如果进度达到100%，自动设置为已完成
        if (progress == 100 && !task.getStatus().equals(3)) {
            task.setStatus(3);
            task.setActualEndTime(LocalDateTime.now());
            task.setCompletionRate(100);
        }

        boolean result = updateById(task);

        if (result) {
            log.info("用户 {} 更新任务 {} 进度为 {}%", userId, task.getTitle(), progress);
            // 记录进度日志、发送通知、更新父任务进度等
            recordTaskLog(id, "PROGRESS_UPDATED",
                String.format("进度更新为 %d%%", progress), userId);
            sendTaskNotification(task, "PROGRESS_UPDATED", userId);
            updateParentTaskProgress(task.getParentId(), userId);

            // 如果进度达到100%，自动完成任务
            if (progress >= 100 && !task.getStatus().equals(3)) {
                updateTaskStatus(id, 3, userId, "进度达到100%，自动完成");
            }
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean logWorkHours(String id, Double hours, String description, String userId) {
        log.info("记录工时: taskId={}, hours={}, userId={}", id, hours, userId);

        if (!StringUtils.hasText(id) || hours == null || hours <= 0) {
            throw new BusinessException("任务ID和工时不能为空，且工时必须大于0");
        }

        Task task = getById(id);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "edit")) {
            throw new BusinessException("无权限记录该任务工时");
        }

        // 更新任务实际工时
        BigDecimal currentActualHours = task.getActualHours() != null ?
            task.getActualHours() : BigDecimal.ZERO;
        BigDecimal newActualHours = currentActualHours.add(BigDecimal.valueOf(hours));

        task.setActualHours(newActualHours);
        task.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(task);

        if (result) {
            // TODO: 创建工时记录到工时记录表
            // 这里需要工时记录表的支持

            String logMessage = String.format("记录工时 %.2f 小时", hours);
            if (StringUtils.hasText(description)) {
                logMessage += "，说明：" + description;
            }

            recordTaskLog(id, "WORK_HOURS_LOGGED", logMessage, userId);
            log.info("工时记录成功: taskId={}, hours={}, totalHours={}",
                    id, hours, newActualHours);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createSubtask(String parentId, Task subtask, String userId) {
        Task parentTask = getById(parentId);
        if (parentTask == null) {
            throw new BusinessException("父任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(parentTask, userId, "edit")) {
            throw new BusinessException("无权限在该任务下创建子任务");
        }

        // 设置子任务信息
        subtask.setParentId(parentId);
        subtask.setProjectId(parentTask.getProjectId());

        boolean result = createTask(subtask, userId);

        if (result) {
            // 更新父任务子任务数量
            parentTask.setSubtaskCount(parentTask.getSubtaskCount() + 1);
            updateById(parentTask);

            log.info("用户 {} 在任务 {} 下创建子任务: {}", userId, parentTask.getTitle(), subtask.getTitle());
        }

        return result;
    }

    @Override
    public List<TaskVO> getSubtasks(String parentId, String userId) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getParentId, parentId)
               .orderByAsc(Task::getSortOrder)
               .orderByDesc(Task::getCreateTime);

        List<Task> subtasks = list(wrapper);

        return subtasks.stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean moveSubtask(String taskId, String newParentId, String userId) {
        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "edit")) {
            throw new BusinessException("无权限移动该任务");
        }

        // 检查新父任务是否存在
        if (StringUtils.hasText(newParentId)) {
            Task newParent = getById(newParentId);
            if (newParent == null) {
                throw new BusinessException("目标父任务不存在");
            }

            // 检查是否会形成循环依赖
            if (isCircularDependency(taskId, newParentId)) {
                throw new BusinessException("不能移动到子任务下，会形成循环依赖");
            }
        }

        String oldParentId = task.getParentId();
        task.setParentId(newParentId);
        task.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(task);

        if (result) {
            log.info("用户 {} 移动子任务 {} 从 {} 到 {}", userId, taskId, oldParentId, newParentId);
            // 更新相关父任务的进度
            updateParentTaskProgress(oldParentId, userId);
            updateParentTaskProgress(newParentId, userId);
            recordTaskLog(taskId, "MOVED", "任务已移动", userId);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTaskDependency(String predecessorId, String successorId, Integer dependencyType, Integer lagDays, String userId) {
        log.info("添加任务依赖: predecessorId={}, successorId={}, dependencyType={}, lagDays={}, userId={}",
                predecessorId, successorId, dependencyType, lagDays, userId);

        // 验证参数
        if (!StringUtils.hasText(predecessorId) || !StringUtils.hasText(successorId)) {
            throw new BusinessException("前置任务ID和后续任务ID不能为空");
        }

        if (predecessorId.equals(successorId)) {
            throw new BusinessException("任务不能依赖自己");
        }

        // 验证任务存在性
        Task predecessor = getById(predecessorId);
        Task successor = getById(successorId);

        if (predecessor == null || successor == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(predecessor, userId, "edit") ||
            !checkTaskPermission(successor, userId, "edit")) {
            throw new BusinessException("无权限操作相关任务");
        }

        // 检查是否会形成循环依赖
        if (wouldCreateCircularDependency(predecessorId, successorId)) {
            throw new BusinessException("添加依赖会形成循环依赖");
        }

        // TODO: 创建任务依赖记录
        // 这里需要任务依赖表的支持
        log.info("任务依赖功能需要依赖表支持，暂时返回成功");

        recordTaskLog(successorId, "DEPENDENCY_ADDED",
                String.format("添加依赖任务: %s", predecessor.getTitle()), userId);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeTaskDependency(String dependencyId, String userId) {
        log.info("移除任务依赖: dependencyId={}, userId={}", dependencyId, userId);

        if (!StringUtils.hasText(dependencyId)) {
            throw new BusinessException("依赖ID不能为空");
        }

        // TODO: 实现依赖移除逻辑
        // 1. 获取依赖记录
        // 2. 验证权限
        // 3. 删除依赖记录
        // 4. 记录日志

        log.info("任务依赖移除功能需要依赖表支持，暂时返回成功");

        return true;
    }

    /**
     * 检查是否会形成循环依赖
     */
    private boolean wouldCreateCircularDependency(String predecessorId, String successorId) {
        // TODO: 实现循环依赖检查逻辑
        // 这需要查询任务依赖表来检查依赖链
        log.debug("检查循环依赖: predecessorId={}, successorId={}", predecessorId, successorId);
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean followTask(String taskId, String userId) {
        log.info("关注任务: taskId={}, userId={}", taskId, userId);

        if (!StringUtils.hasText(taskId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("任务ID和用户ID不能为空");
        }

        // 验证任务存在性
        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "read")) {
            throw new BusinessException("无权限访问该任务");
        }

        // TODO: 实现任务关注逻辑
        // 1. 检查是否已关注
        // 2. 添加关注记录到任务关注表
        // 3. 更新任务关注统计

        log.info("任务关注功能需要关注表支持，暂时返回成功");
        recordTaskLog(taskId, "FOLLOWED", "用户开始关注任务", userId);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unfollowTask(String taskId, String userId) {
        log.info("取消关注任务: taskId={}, userId={}", taskId, userId);

        if (!StringUtils.hasText(taskId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("任务ID和用户ID不能为空");
        }

        // 验证任务存在性
        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // TODO: 实现取消关注逻辑
        // 1. 检查是否已关注
        // 2. 删除关注记录
        // 3. 更新任务关注统计

        log.info("取消任务关注功能需要关注表支持，暂时返回成功");
        recordTaskLog(taskId, "UNFOLLOWED", "用户取消关注任务", userId);

        return true;
    }

    @Override
    public PageResult<TaskVO> getMyCreatedTasks(String userId, Integer pageNum, Integer pageSize) {
        Page<Task> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getCreatorId, userId)
               .orderByDesc(Task::getCreateTime);

        IPage<Task> result = page(page, wrapper);

        List<TaskVO> voList = result.getRecords().stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    public PageResult<TaskVO> getMyFollowedTasks(String userId, Integer pageNum, Integer pageSize) {
        log.info("查询我关注的任务: userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize);

        // TODO: 实现我关注的任务查询
        // 这需要任务关注表的支持
        // 1. 查询用户关注的任务ID列表
        // 2. 根据任务ID列表查询任务详情
        // 3. 分页返回结果

        // 暂时返回空结果，实际实现需要关注表支持
        log.info("我关注的任务查询功能需要关注表支持，暂时返回空结果");
        return PageResult.of(List.of(), 0L);
    }

    @Override
    public PageResult<TaskVO> getOverdueTasks(String userId, Integer pageNum, Integer pageSize) {
        Page<Task> page = new Page<>(pageNum, pageSize);

        LocalDateTime now = LocalDateTime.now();

        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAssigneeId, userId)
               .in(Task::getStatus, 1, 2) // 待办或进行中
               .lt(Task::getPlannedEndTime, now) // 计划结束时间小于当前时间
               .orderByAsc(Task::getPlannedEndTime);

        IPage<Task> result = page(page, wrapper);

        List<TaskVO> voList = result.getRecords().stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    public List<TaskVO> getWeekTasks(String userId) {
        LocalDateTime startOfWeek = LocalDateTime.now().with(java.time.DayOfWeek.MONDAY).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfWeek = startOfWeek.plusDays(6).withHour(23).withMinute(59).withSecond(59);

        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAssigneeId, userId)
               .in(Task::getStatus, 1, 2) // 待办或进行中
               .and(w -> w.between(Task::getPlannedStartTime, startOfWeek, endOfWeek)
                         .or()
                         .between(Task::getPlannedEndTime, startOfWeek, endOfWeek))
               .orderByAsc(Task::getPriority)
               .orderByAsc(Task::getPlannedEndTime);

        List<Task> tasks = list(wrapper);

        return tasks.stream()
            .map(task -> convertToVO(task, userId))
            .collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getTaskStatistics(String userId, String projectId, LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> statistics = new HashMap<>();

        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAssigneeId, userId);

        if (StringUtils.hasText(projectId)) {
            wrapper.eq(Task::getProjectId, projectId);
        }

        if (startTime != null && endTime != null) {
            wrapper.between(Task::getCreateTime, startTime, endTime);
        }

        List<Task> tasks = list(wrapper);

        // 统计各状态任务数量
        Map<Integer, Long> statusCount = tasks.stream()
                .collect(Collectors.groupingBy(Task::getStatus, Collectors.counting()));

        // 统计各优先级任务数量
        Map<Integer, Long> priorityCount = tasks.stream()
                .collect(Collectors.groupingBy(Task::getPriority, Collectors.counting()));

        statistics.put("totalTasks", tasks.size());
        statistics.put("statusCount", statusCount);
        statistics.put("priorityCount", priorityCount);
        statistics.put("completedTasks", statusCount.getOrDefault(3, 0L));
        statistics.put("overdueTasks", tasks.stream()
                .filter(task -> task.getPlannedEndTime() != null &&
                               task.getPlannedEndTime().isBefore(LocalDateTime.now()) &&
                               !task.getStatus().equals(3))
                .count());

        return statistics;
    }

    @Override
    public List<Map<String, Object>> getTaskCompletionTrend(String userId, Integer days) {
        List<Map<String, Object>> trend = new ArrayList<>();

        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days);

        // 按天统计完成的任务数量
        for (int i = 0; i < days; i++) {
            LocalDateTime dayStart = startTime.plusDays(i).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime dayEnd = dayStart.withHour(23).withMinute(59).withSecond(59);

            LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Task::getAssigneeId, userId)
                   .eq(Task::getStatus, 3) // 已完成
                   .between(Task::getUpdateTime, dayStart, dayEnd);

            long count = count(wrapper);

            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", dayStart.toLocalDate().toString());
            dayData.put("completedCount", count);
            trend.add(dayData);
        }

        return trend;
    }

    @Override
    public List<Map<String, Object>> getTaskPriorityDistribution(String userId, String projectId) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAssigneeId, userId);

        if (StringUtils.hasText(projectId)) {
            wrapper.eq(Task::getProjectId, projectId);
        }

        List<Task> tasks = list(wrapper);

        // 按优先级分组统计
        Map<Integer, Long> priorityCount = tasks.stream()
                .collect(Collectors.groupingBy(Task::getPriority, Collectors.counting()));

        List<Map<String, Object>> distribution = new ArrayList<>();

        // 转换为前端需要的格式
        priorityCount.forEach((priority, count) -> {
            Map<String, Object> item = new HashMap<>();
            item.put("priority", priority);
            item.put("priorityText", getPriorityText(priority));
            item.put("count", count);
            item.put("percentage", tasks.isEmpty() ? 0 : (count * 100.0 / tasks.size()));
            distribution.add(item);
        });

        return distribution;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTaskFromTemplate(String templateId, Map<String, Object> customData, String userId) {
        log.info("从模板创建任务: templateId={}, userId={}", templateId, userId);

        // TODO: 集成任务模板服务
        // 1. 获取模板信息
        // 2. 根据模板创建任务
        // 3. 应用自定义数据
        // 4. 保存任务

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAsTemplate(String taskId, String templateName, String userId) {
        log.info("保存任务为模板: taskId={}, templateName={}, userId={}", taskId, templateName, userId);

        Task task = getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 权限检查
        if (!checkTaskPermission(task, userId, "read")) {
            throw new BusinessException("无权限访问该任务");
        }

        // TODO: 集成任务模板服务
        // 1. 创建模板记录
        // 2. 保存任务信息到模板
        // 3. 处理关联数据

        return false;
    }

    @Override
    public String exportTasks(List<String> taskIds, String format, String userId) {
        log.info("导出任务: taskIds={}, format={}, userId={}", taskIds, format, userId);

        // 参数验证
        if (taskIds == null || taskIds.isEmpty()) {
            throw new BusinessException("任务ID列表不能为空");
        }

        if (!isValidExportFormat(format)) {
            throw new BusinessException("不支持的导出格式: " + format);
        }

        try {
            // 1. 验证权限并获取任务数据
            List<Task> tasks = validateAndGetTasks(taskIds, userId);

            // 2. 根据格式生成文件
            String fileName = generateExportFileName(format, userId);
            String filePath = generateExportFile(tasks, format, fileName);

            log.info("任务导出成功: userId={}, taskCount={}, format={}, filePath={}",
                    userId, tasks.size(), format, filePath);

            return filePath;

        } catch (Exception e) {
            log.error("导出任务失败: userId={}, taskIds={}, format={}", userId, taskIds, format, e);
            throw new BusinessException("导出任务失败: " + e.getMessage());
        }
    }

    /**
     * 验证导出格式
     */
    private boolean isValidExportFormat(String format) {
        return format != null && format.matches("(?i)(excel|csv|json|pdf)");
    }

    /**
     * 验证权限并获取任务数据
     */
    private List<Task> validateAndGetTasks(List<String> taskIds, String userId) {
        List<Task> tasks = new ArrayList<>();

        for (String taskId : taskIds) {
            Task task = getById(taskId);
            if (task == null) {
                log.warn("任务不存在: taskId={}", taskId);
                continue;
            }

            // 权限检查
            if (!checkTaskPermission(task, userId, "read")) {
                log.warn("无权限访问任务: taskId={}, userId={}", taskId, userId);
                continue;
            }

            tasks.add(task);
        }

        if (tasks.isEmpty()) {
            throw new BusinessException("没有可导出的任务");
        }

        return tasks;
    }

    /**
     * 生成导出文件名
     */
    private String generateExportFileName(String format, String userId) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        return String.format("tasks_export_%s_%s.%s", userId, timestamp, format.toLowerCase());
    }

    /**
     * 生成导出文件
     */
    private String generateExportFile(List<Task> tasks, String format, String fileName) {
        // TODO: 实现具体的文件生成逻辑
        // 这里需要根据不同格式生成相应的文件

        String exportDir = "/exports/tasks/";
        String filePath = exportDir + fileName;

        switch (format.toLowerCase()) {
            case "excel":
                generateExcelFile(tasks, filePath);
                break;
            case "csv":
                generateCsvFile(tasks, filePath);
                break;
            case "json":
                generateJsonFile(tasks, filePath);
                break;
            case "pdf":
                generatePdfFile(tasks, filePath);
                break;
            default:
                throw new BusinessException("不支持的导出格式: " + format);
        }

        return filePath;
    }

    /**
     * 生成Excel文件
     */
    private void generateExcelFile(List<Task> tasks, String filePath) {
        // TODO: 实现Excel文件生成
        log.info("生成Excel文件: filePath={}, taskCount={}", filePath, tasks.size());
    }

    /**
     * 生成CSV文件
     */
    private void generateCsvFile(List<Task> tasks, String filePath) {
        // TODO: 实现CSV文件生成
        log.info("生成CSV文件: filePath={}, taskCount={}", filePath, tasks.size());
    }

    /**
     * 生成JSON文件
     */
    private void generateJsonFile(List<Task> tasks, String filePath) {
        // TODO: 实现JSON文件生成
        log.info("生成JSON文件: filePath={}, taskCount={}", filePath, tasks.size());
    }

    /**
     * 生成PDF文件
     */
    private void generatePdfFile(List<Task> tasks, String filePath) {
        // TODO: 实现PDF文件生成
        log.info("生成PDF文件: filePath={}, taskCount={}", filePath, tasks.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importTasks(String filePath, String userId) {
        log.info("导入任务: filePath={}, userId={}", filePath, userId);

        Map<String, Object> result = new HashMap<>();

        // 参数验证
        if (!StringUtils.hasText(filePath) || !StringUtils.hasText(userId)) {
            throw new BusinessException("文件路径和用户ID不能为空");
        }

        try {
            // 1. 解析文件
            List<Map<String, Object>> taskDataList = parseImportFile(filePath);

            // 2. 验证数据
            List<Map<String, Object>> validTasks = validateImportData(taskDataList);

            // 3. 批量创建任务
            ImportResult importResult = batchCreateTasks(validTasks, userId);

            // 4. 返回导入结果
            result.put("success", true);
            result.put("message", "导入完成");
            result.put("totalCount", taskDataList.size());
            result.put("importedCount", importResult.getSuccessCount());
            result.put("failedCount", importResult.getFailedCount());
            result.put("failedTasks", importResult.getFailedTasks());

            log.info("任务导入完成: userId={}, total={}, success={}, failed={}",
                    userId, taskDataList.size(), importResult.getSuccessCount(), importResult.getFailedCount());

        } catch (Exception e) {
            log.error("导入任务失败: filePath={}, userId={}", filePath, userId, e);
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
            result.put("importedCount", 0);
            result.put("failedCount", 0);
        }

        return result;
    }

    /**
     * 解析导入文件
     */
    private List<Map<String, Object>> parseImportFile(String filePath) {
        // TODO: 实现文件解析逻辑
        // 根据文件扩展名选择不同的解析器

        String fileExtension = getFileExtension(filePath);

        switch (fileExtension.toLowerCase()) {
            case "xlsx":
            case "xls":
                return parseExcelFile(filePath);
            case "csv":
                return parseCsvFile(filePath);
            case "json":
                return parseJsonFile(filePath);
            default:
                throw new BusinessException("不支持的文件格式: " + fileExtension);
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filePath) {
        int lastDotIndex = filePath.lastIndexOf('.');
        return lastDotIndex > 0 ? filePath.substring(lastDotIndex + 1) : "";
    }

    /**
     * 解析Excel文件
     */
    private List<Map<String, Object>> parseExcelFile(String filePath) {
        // TODO: 实现Excel文件解析
        log.info("解析Excel文件: {}", filePath);
        return new ArrayList<>();
    }

    /**
     * 解析CSV文件
     */
    private List<Map<String, Object>> parseCsvFile(String filePath) {
        // TODO: 实现CSV文件解析
        log.info("解析CSV文件: {}", filePath);
        return new ArrayList<>();
    }

    /**
     * 解析JSON文件
     */
    private List<Map<String, Object>> parseJsonFile(String filePath) {
        // TODO: 实现JSON文件解析
        log.info("解析JSON文件: {}", filePath);
        return new ArrayList<>();
    }

    /**
     * 验证导入数据
     */
    private List<Map<String, Object>> validateImportData(List<Map<String, Object>> taskDataList) {
        List<Map<String, Object>> validTasks = new ArrayList<>();

        for (Map<String, Object> taskData : taskDataList) {
            if (isValidTaskData(taskData)) {
                validTasks.add(taskData);
            } else {
                log.warn("无效的任务数据: {}", taskData);
            }
        }

        return validTasks;
    }

    /**
     * 验证任务数据
     */
    private boolean isValidTaskData(Map<String, Object> taskData) {
        // 检查必填字段
        return taskData.containsKey("title") &&
               StringUtils.hasText((String) taskData.get("title"));
    }

    /**
     * 批量创建任务
     */
    private ImportResult batchCreateTasks(List<Map<String, Object>> validTasks, String userId) {
        ImportResult result = new ImportResult();

        for (Map<String, Object> taskData : validTasks) {
            try {
                Task task = createTaskFromImportData(taskData, userId);
                boolean success = save(task);

                if (success) {
                    result.incrementSuccess();
                    recordTaskLog(task.getId(), "IMPORTED", "任务从文件导入", userId);
                } else {
                    result.incrementFailed();
                    result.addFailedTask(taskData, "保存任务失败");
                }

            } catch (Exception e) {
                result.incrementFailed();
                result.addFailedTask(taskData, e.getMessage());
                log.error("创建任务失败: taskData={}", taskData, e);
            }
        }

        return result;
    }

    /**
     * 从导入数据创建任务
     */
    private Task createTaskFromImportData(Map<String, Object> taskData, String userId) {
        Task task = new Task();

        // 设置基础信息
        task.setTitle((String) taskData.get("title"));
        task.setDescription((String) taskData.getOrDefault("description", ""));
        task.setCreatorId(userId);
        task.setAssigneeId((String) taskData.getOrDefault("assigneeId", userId));
        task.setStatus((Integer) taskData.getOrDefault("status", 1));
        task.setPriority((Integer) taskData.getOrDefault("priority", 2));
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());

        // 设置可选字段
        if (taskData.containsKey("projectId")) {
            task.setProjectId((String) taskData.get("projectId"));
        }

        return task;
    }

    /**
     * 导入结果类
     */
    private static class ImportResult {
        private int successCount = 0;
        private int failedCount = 0;
        private List<Map<String, Object>> failedTasks = new ArrayList<>();

        public void incrementSuccess() {
            successCount++;
        }

        public void incrementFailed() {
            failedCount++;
        }

        public void addFailedTask(Map<String, Object> taskData, String reason) {
            Map<String, Object> failedTask = new HashMap<>();
            failedTask.put("data", taskData);
            failedTask.put("reason", reason);
            failedTasks.add(failedTask);
        }

        public int getSuccessCount() {
            return successCount;
        }

        public int getFailedCount() {
            return failedCount;
        }

        public List<Map<String, Object>> getFailedTasks() {
            return failedTasks;
        }
    }
}
